import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';

void main() {
  const MethodChannel channel = MethodChannel('flutter_openim_sdk');

  TestWidgetsFlutterBinding.ensureInitialized();

  setUp(() {
    channel.setMockMethodCallHandler((MethodCall methodCall) async {
      switch (methodCall.method) {
        case 'initSDK':
          return true;
        case 'login':
          return true;
        case 'getLoginStatus':
          return 0;
        case 'logout':
          return true;
        case 'getUsersInfo':
          return jsonEncode([
            {
              'userID': 'user1',
              'nickname': 'User One',
              'faceURL': 'https://example.com/avatar1.jpg'
            }
          ]);
        case 'setSelfInfo':
          return 'success';
        case 'getSelfUserInfo':
          return jsonEncode({
            'userID': 'test_user',
            'nickname': 'Test User',
            'faceURL': 'https://example.com/test_avatar.jpg'
          });
        default:
          return null;
      }
    });
  });

  tearDown(() {
    channel.setMockMethodCallHandler(null);
  });

  test('initSDK', () async {
    final result = await OpenIM.iMManager.initSDK(
        platformID: 2,
        apiAddr: 'http://10.50.80.28:10002',
        wsAddr: 'ws://10.50.80.28:10001',
        dataDir: '/data/storage/el2/base/haps/entry/files',
        listener: OnConnectListener());
    expect(result, true);
  });

  test('login', () async {
    final result = await OpenIM.iMManager.login(
        userID: 'test_user', token: 'test_token', operationID: '1368103760');
    expect(result is UserInfo, true);
  });

  test('logout', () async {
    final result = await OpenIM.iMManager.logout(operationID: '1368103760');
    expect(result, true);
  });

  test('getLoginStatus', () async {
    final result = await OpenIM.iMManager.getLoginStatus(operationID: '123456');
    expect(result, 0);
  });

  test('getUsersInfo', () async {
    final result = await OpenIM.iMManager.userManager
        .getUsersInfo(userIDList: ['user1'], operationID: '123456');
    expect(result.isNotEmpty, true);
    expect(result.first.userID, 'user1');
    expect(result.first.nickname, 'User One');
  });

  test('setSelfInfo', () async {
    final result = await OpenIM.iMManager.userManager.setSelfInfo(
        nickname: 'New Nickname',
        faceURL: 'https://example.com/new_avatar.jpg',
        operationID: '123456');
    expect(result, 'success');
  });

  test('login functionality', () async {
    final result = await OpenIM.iMManager
        .login(userID: 'test_user', token: 'test_token', operationID: '123456');
    expect(result is UserInfo, true);
  });
}
